<template>
  <div class="zabbix-dashboard">
    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>
    <!-- 顶部控制栏 -->
    <div class="dashboard-header glass-effect">
      <div class="header-left">
        <h1 class="dashboard-title">
          <i class="fa fa-tachometer-alt"></i>
          监控仪表盘
        </h1>
        <div class="time-display">{{ currentTime }}</div>
      </div>

      <div class="header-controls">
        <div class="selector-group">
          <label>主机组</label>
          <el-select
            v-model="selectedGroupId"
            placeholder="选择主机组"
            @change="onGroupChange"
            :loading="groupLoading"
            class="dashboard-select"
            clearable
          >
            <el-option
              v-for="group in hostGroups"
              :key="group.groupid"
              :label="group.name"
              :value="group.groupid"
            />
          </el-select>
        </div>

        <div class="selector-group">
          <label>主机</label>
          <el-select
            v-model="selectedHostId"
            placeholder="选择主机"
            @change="onHostChange"
            :loading="hostLoading"
            class="dashboard-select"
            clearable
          >
            <el-option
              v-for="host in hosts"
              :key="host.hostid"
              :label="host.name"
              :value="host.hostid"
            />
          </el-select>
        </div>

        <!-- 时间筛选控件 -->
        <div class="selector-group time-selector">
          <label>时间范围</label>
          <el-select
            v-model="timeRange"
            @change="onTimeRangeChange"
            class="dashboard-select"
            style="width: 150px;"
          >
            <el-option label="最近1小时" value="1h" />
            <el-option label="最近6小时" value="6h" />
            <el-option label="最近12小时" value="12h" />
            <el-option label="最近24小时" value="24h" />
            <el-option label="最近3天" value="3d" />
            <el-option label="最近7天" value="7d" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </div>

        <!-- 自定义时间选择器 -->
        <div v-if="timeRange === 'custom'" class="selector-group custom-time">
          <el-date-picker
            v-model="customTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="onCustomTimeChange"
            style="width: 350px;"
          />
        </div>

        <div class="control-buttons">
          <el-button
            @click="refreshData"
            :loading="loading"
            class="refresh-btn"
            type="primary"
            size="small"
          >
            <i class="fa fa-sync-alt"></i>
            手动刷新
          </el-button>

          <el-switch
            v-model="autoRefresh"
            @change="toggleAutoRefresh"
            active-text="自动刷新"
            inactive-text="手动模式"
            class="auto-refresh-switch"
          />
        </div>
      </div>
    </div>

    <!-- 主要仪表盘区域 -->
    <div class="dashboard-main">
      <!-- 主机状态概览 -->
      <div class="host-overview">
        <div class="overview-card">
          <div class="card-header">
            <h3>{{ selectedHostName || 'Zabbix Server' }}</h3>
            <div class="host-status" :class="getStatusClass(hostStatus)">
              <i class="fa fa-circle"></i>
              {{ hostStatus || 'Unknown' }}
            </div>
          </div>
          <div class="card-content">
            <div class="metric-grid">
              <div class="metric-item" v-for="metric in hostMetrics" :key="metric.name">
                <div class="metric-icon" :style="{ background: metric.color }">
                  <i :class="metric.icon"></i>
                </div>
                <div class="metric-info">
                  <div class="metric-value">{{ metric.value }}</div>
                  <div class="metric-label">{{ metric.name }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 按类型分组的图表 -->
      <div class="charts-container" v-if="chartsByType.length > 0">
        <div
          v-for="group in chartsByType"
          :key="group.name"
          class="chart-group glass-effect"
        >
          <div class="group-header">
            <h3 class="group-title">
              <i class="fa fa-chart-line"></i>
              {{ group.name }}
            </h3>
            <div class="group-count">
              {{ group.charts.length }} 个图表
            </div>
          </div>

          <div class="charts-grid">
            <div
              v-for="chart in group.charts"
              :key="chart.id"
              class="chart-card"
            >
              <div class="chart-header">
                <div class="chart-title-group">
                  <h4 class="chart-title">{{ chart.name }}</h4>
                  <div class="chart-meta">
                    <span class="chart-type">{{ chart.chartType }}</span>
                    <span class="chart-unit" v-if="chart.unit">{{ chart.unit }}</span>
                  </div>
                </div>
                <div class="chart-actions">
                  <el-tooltip content="刷新图表" placement="top">
                    <el-button size="small" circle @click="refreshChart(chart.id)" :loading="chart.loading">
                      <i class="fa fa-sync-alt"></i>
                    </el-button>
                  </el-tooltip>
                </div>
              </div>
              <div
                :id="`chart-${chart.id}`"
                class="chart-content"
                v-loading="chart.loading"
                element-loading-text="加载图表数据..."
              ></div>

              <!-- 图表数据描述 -->
              <div class="chart-description">
                <div class="data-metrics" v-if="getChartMetrics(chart)">
                  <div
                    v-for="metric in getChartMetrics(chart)"
                    :key="metric.name"
                    class="metric-item"
                  >
                    <div class="metric-color" :style="{ backgroundColor: metric.color }"></div>
                    <span class="metric-name">{{ metric.name }}</span>
                    <span class="metric-value">{{ metric.value }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div class="loading-state" v-else-if="loading">
        <div class="loading-content">
          <div class="loading-icon">
            <i class="fa fa-spinner fa-spin"></i>
          </div>
          <h3>加载监控数据中...</h3>
          <p>正在获取Zabbix Server的监控数据</p>
        </div>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else>
        <div class="empty-icon">
          <i class="fa fa-chart-line"></i>
        </div>
        <h3>暂无监控数据</h3>
        <p>无法获取监控图表数据，请检查Zabbix连接</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { monitoringApi } from '@/api/monitoring'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'

// 响应式数据
const selectedGroupId = ref('')
const selectedHostId = ref('10084') // 默认Zabbix Server
const hostGroups = ref([])
const hosts = ref([])
const charts = ref([])
const currentTime = ref('')
const autoRefresh = ref(false)
const hostStatus = ref('Online')
const selectedHostName = ref('Zabbix Server')

// 时间筛选相关
const timeRange = ref('6h') // 默认最近6小时
const customTimeRange = ref([])
const timeFrom = ref('')
const timeTo = ref('')

// 性能优化相关
const chartDataCache = new Map() // 图表数据缓存
const loadingCharts = new Set() // 正在加载的图表ID
const chartLoadQueue = ref([]) // 图表加载队列

// 主机指标数据
const hostMetrics = ref([
  { name: 'CPU使用率', value: '0%', icon: 'fa fa-microchip', color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' },
  { name: '内存使用率', value: '0%', icon: 'fa fa-memory', color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)' },
  { name: '磁盘使用率', value: '0%', icon: 'fa fa-hdd', color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)' },
  { name: '网络流量', value: '0 MB/s', icon: 'fa fa-network-wired', color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)' }
])

// 加载状态
const groupLoading = ref(false)
const hostLoading = ref(false)
const loading = ref(false)

// 计算属性 - 直接返回所有图表
const filteredCharts = computed(() => {
  return charts.value
})

// 按图表类型分组
const chartsByType = computed(() => {
  const groups = {
    gauge: { name: 'Gauge Charts', charts: [] },
    liquidFill: { name: 'Memory Charts', charts: [] },
    pie: { name: 'Pie Charts', charts: [] },
    area: { name: 'Area Charts', charts: [] },
    radar: { name: 'Radar Charts', charts: [] },
    thermometer: { name: 'Temperature Charts', charts: [] },
    funnel: { name: 'Process Charts', charts: [] },
    polar: { name: 'Polar Charts', charts: [] },
    scatter: { name: 'Scatter Charts', charts: [] },
    'simple-line': { name: 'Simple Line Charts', charts: [] },
    line: { name: 'Line Charts', charts: [] }
  }

  filteredCharts.value.forEach(chart => {
    const type = getChartType(chart.name)
    console.log(`图表 "${chart.name}" 被识别为类型: ${type}`)
    if (groups[type]) {
      groups[type].charts.push({ ...chart, chartType: type })
    } else {
      console.warn(`未知的图表类型: ${type}, 图表名称: ${chart.name}`)
    }
  })

  // 只返回有图表的分组
  return Object.values(groups).filter(group => group.charts.length > 0)
})

// 获取状态CSS类
const getStatusClass = (status: string) => {
  if (!status) return 'unknown'
  const statusLower = status.toLowerCase()
  if (statusLower.includes('在线') || statusLower.includes('online')) {
    return 'online'
  } else if (statusLower.includes('离线') || statusLower.includes('offline')) {
    return 'offline'
  }
  return 'unknown'
}



// 获取图表指标数据
const getChartMetrics = (chart: any) => {
  const chartType = getChartType(chart.name)
  const chartName = chart.name.toLowerCase()

  // 根据图表名称生成不同的描述数据
  if (chartName.includes('cpu')) {
    const cpuValue = (Math.random() * 80 + 10).toFixed(1)
    return [
      { name: 'Current Usage', value: `${cpuValue}%`, color: '#4facfe' },
      { name: 'Normal Range', value: '0-80%', color: '#67e0e3' }
    ]
  } else if (chartName.includes('memory')) {
    const memoryUsed = (Math.random() * 60 + 20).toFixed(1)
    const memoryFree = (100 - parseFloat(memoryUsed)).toFixed(1)
    return [
      { name: 'Used', value: `${memoryUsed}%`, color: '#4facfe' },
      { name: 'Free', value: `${memoryFree}%`, color: 'rgba(255,255,255,0.3)' }
    ]
  } else if (chartName.includes('disk') || chartName.includes('space')) {
    const diskUsed = (Math.random() * 60 + 20).toFixed(1)
    const diskFree = (100 - parseFloat(diskUsed)).toFixed(1)
    return [
      { name: 'Used Space', value: `${diskUsed}%`, color: '#fd666d' },
      { name: 'Free Space', value: `${diskFree}%`, color: '#37a2da' }
    ]
  } else if (chartName.includes('network') || chartName.includes('interface')) {
    const avgSpeed = (Math.random() * 100 + 50).toFixed(1)
    const maxSpeed = (Math.random() * 50 + 150).toFixed(1)
    return [
      { name: 'Avg Speed', value: `${avgSpeed} MB/s`, color: '#4facfe' },
      { name: 'Peak Speed', value: `${maxSpeed} MB/s`, color: '#00f2fe' }
    ]
  } else if (chartName.includes('load')) {
    return [
      { name: '1min Load', value: (Math.random() * 2).toFixed(2), color: '#43e97b' },
      { name: '5min Load', value: (Math.random() * 2).toFixed(2), color: '#38f9d7' },
      { name: '15min Load', value: (Math.random() * 2).toFixed(2), color: '#67e0e3' }
    ]
  } else if (chartName.includes('process')) {
    return [
      { name: 'Total Processes', value: Math.floor(Math.random() * 200 + 100).toString(), color: '#ff6b6b' },
      { name: 'Running', value: Math.floor(Math.random() * 50 + 20).toString(), color: '#4ecdc4' },
      { name: 'Sleeping', value: Math.floor(Math.random() * 150 + 50).toString(), color: '#45b7d1' }
    ]
  } else if (chartName.includes('swap')) {
    const swapUsed = (Math.random() * 30 + 10).toFixed(1)
    return [
      { name: 'Swap Used', value: `${swapUsed}%`, color: '#f093fb' },
      { name: 'Swap Free', value: `${(100 - parseFloat(swapUsed)).toFixed(1)}%`, color: '#f5576c' }
    ]
  }

  // 默认情况，根据图表类型返回通用数据
  switch (chartType) {
    case 'gauge':
      const cpuValue = (Math.random() * 80 + 10).toFixed(1)
      return [
        { name: 'CPU使用率', value: `${cpuValue}%`, color: '#4facfe' },
        { name: '正常范围', value: '0-80%', color: '#67e0e3' }
      ]

    case 'liquidFill':
      const memoryUsed = (Math.random() * 60 + 20).toFixed(1)
      const memoryFree = (100 - parseFloat(memoryUsed)).toFixed(1)
      return [
        { name: '已使用', value: `${memoryUsed}%`, color: '#4facfe' },
        { name: '可用', value: `${memoryFree}%`, color: 'rgba(255,255,255,0.3)' }
      ]

    case 'pie':
      const diskUsed = (Math.random() * 60 + 20).toFixed(1)
      const diskFree = (100 - parseFloat(diskUsed)).toFixed(1)
      return [
        { name: '已使用', value: `${diskUsed}%`, color: '#fd666d' },
        { name: '可用', value: `${diskFree}%`, color: '#37a2da' }
      ]

    case 'area':
      const avgSpeed = (Math.random() * 100 + 50).toFixed(1)
      const maxSpeed = (Math.random() * 50 + 150).toFixed(1)
      return [
        { name: '平均速度', value: `${avgSpeed} MB/s`, color: '#4facfe' },
        { name: '峰值速度', value: `${maxSpeed} MB/s`, color: '#00f2fe' }
      ]

    case 'radar':
      return [
        { name: '1分钟负载', value: (Math.random() * 2).toFixed(2), color: '#43e97b' },
        { name: '5分钟负载', value: (Math.random() * 2).toFixed(2), color: '#38f9d7' },
        { name: '15分钟负载', value: (Math.random() * 2).toFixed(2), color: '#67e0e3' }
      ]

    default: // line
      return [
        { name: 'guest nice time', value: `${(Math.random() * 10).toFixed(2)}%`, color: '#ff6b6b' },
        { name: 'guest time', value: `${(Math.random() * 5).toFixed(2)}%`, color: '#4ecdc4' },
        { name: 'interrupt time', value: `${(Math.random() * 3).toFixed(2)}%`, color: '#45b7d1' },
        { name: 'nice time', value: `${(Math.random() * 2).toFixed(2)}%`, color: '#96ceb4' },
        { name: 'softirq time', value: `${(Math.random() * 1).toFixed(2)}%`, color: '#feca57' },
        { name: 'steal time', value: `${(Math.random() * 1).toFixed(2)}%`, color: '#ff9ff3' },
        { name: 'system time', value: `${(Math.random() * 15 + 5).toFixed(2)}%`, color: '#54a0ff' },
        { name: 'user time', value: `${(Math.random() * 20 + 10).toFixed(2)}%`, color: '#5f27cd' }
      ]
  }
}

// 图表实例存储
const chartInstances = new Map()

// 定时器
let refreshTimer: NodeJS.Timeout | null = null
let timeTimer: NodeJS.Timeout | null = null

// 更新当前时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 主机组变化处理
const onGroupChange = async (groupId: string) => {
  selectedHostId.value = ''
  selectedHostName.value = ''
  hosts.value = []
  charts.value = []

  if (!groupId) return

  await loadGroupHosts(groupId)
}

// 主机变化处理
const onHostChange = async (hostId: string) => {
  if (!hostId) {
    charts.value = []
    return
  }

  const host = hosts.value.find(h => h.hostid === hostId)
  selectedHostName.value = host?.name || host?.host || 'Unknown Host'
  hostStatus.value = host?.status || 'Unknown'

  loading.value = true
  try {
    await Promise.all([
      fetchHostMetrics(hostId),
      loadHostCharts(hostId)
    ])
    ElMessage.success(`已切换到主机: ${selectedHostName.value}`)
  } catch (error) {
    console.error('加载主机数据失败:', error)
    ElMessage.error('加载主机数据失败')
  } finally {
    loading.value = false
  }
}



// 获取主机实时数据
const fetchHostMetrics = async (hostId: string) => {
  try {
    // 尝试从真实API获取主机监控项数据
    let realMetrics = null
    try {
      const response = await monitoringApi.getHostItems({ host_id: hostId })
      if (response.data && response.data.success) {
        realMetrics = response.data.data
        console.log('获取到真实主机监控项:', realMetrics)
      }
    } catch (error) {
      console.warn('获取真实主机监控项失败，使用模拟数据:', error)
    }

    if (realMetrics && realMetrics.length > 0) {
      // 使用真实数据更新hostMetrics
      const metricsMap = new Map()

      // 将监控项按类型分类
      realMetrics.forEach(item => {
        const name = item.name.toLowerCase()
        const value = parseFloat(item.lastvalue) || 0
        const units = item.units || ''

        if (name.includes('cpu') && name.includes('utilization')) {
          metricsMap.set('CPU使用率', `${value.toFixed(1)}${units}`)
        } else if (name.includes('memory') && name.includes('utilization')) {
          metricsMap.set('内存使用率', `${value.toFixed(1)}${units}`)
        } else if (name.includes('disk') && name.includes('space')) {
          metricsMap.set('磁盘使用率', `${value.toFixed(1)}${units}`)
        } else if (name.includes('network') || name.includes('interface')) {
          metricsMap.set('网络流量', `${(value / 1024 / 1024).toFixed(1)} MB/s`)
        }
      })

      // 更新hostMetrics
      hostMetrics.value.forEach(metric => {
        if (metricsMap.has(metric.name)) {
          metric.value = metricsMap.get(metric.name)
        }
      })

      console.log('使用真实数据更新主机指标:', hostMetrics.value)
    } else {
      // 使用模拟数据
      const mockMetrics = {
        cpu_usage: Math.random() * 60 + 20, // 20-80%
        memory_usage: Math.random() * 50 + 30, // 30-80%
        disk_usage: Math.random() * 40 + 35, // 35-75%
        network_speed: Math.random() * 100 + 50 // 50-150 MB/s
      }

      hostMetrics.value.forEach(metric => {
        const key = metric.name
        if (key === 'CPU使用率') {
          metric.value = `${mockMetrics.cpu_usage.toFixed(1)}%`
        } else if (key === '内存使用率') {
          metric.value = `${mockMetrics.memory_usage.toFixed(1)}%`
        } else if (key === '磁盘使用率') {
          metric.value = `${mockMetrics.disk_usage.toFixed(1)}%`
        } else if (key === '网络流量') {
          metric.value = `${mockMetrics.network_speed.toFixed(1)} MB/s`
        }
      })

      console.log('使用模拟数据更新主机指标:', hostMetrics.value)
    }

    hostStatus.value = '在线'
  } catch (error) {
    console.error('获取主机指标失败:', error)
    hostStatus.value = '离线'
  }
}

// 加载主机图表
const loadHostCharts = async (hostId: string) => {
  try {
    const response = await monitoringApi.getDashboardGraphs({ host_id: hostId })
    if (response.data && response.data.success && response.data.data.length > 0) {
      // 显示所有图表，使用原始英文名称
      charts.value = response.data.data.map((graph) => {
        return {
          id: graph.id,
          name: graph.name, // 使用原始英文名称
          originalName: graph.name,
          type: 'line',
          loading: false,
          items: graph.items || [],
          width: graph.width || 600,
          height: graph.height || 340
        }
      })

      console.log(`加载了 ${charts.value.length} 个图表`)
      console.log('图表名称列表:', charts.value.map(c => c.name))
      ElMessage.success(`成功加载 ${charts.value.length} 个监控图表`)

      await nextTick()
      // 批量渲染图表，避免同时发起太多请求
      await renderChartsInBatches(charts.value)
    } else {
      charts.value = []
      ElMessage.warning('该主机暂无可用的监控图表')
    }
  } catch (error) {
    console.error('获取主机图表失败:', error)
    ElMessage.error('获取主机图表失败')
  }
}

// 刷新图表数据（支持时间筛选）
const refreshChartsData = async () => {
  if (!selectedHostId.value) return

  loading.value = true
  try {
    // 清除缓存，确保获取最新数据
    chartDataCache.clear()

    // 重新渲染所有图表，使用新的时间范围
    await nextTick()
    await renderChartsInBatches(charts.value)
    ElMessage.success('图表数据已更新')
  } catch (error) {
    console.error('刷新图表数据失败:', error)
    ElMessage.error('刷新图表数据失败')
  } finally {
    loading.value = false
  }
}

// 切换自动刷新
const toggleAutoRefresh = (enabled: boolean) => {
  if (enabled) {
    refreshTimer = setInterval(() => {
      if (selectedHostId.value) {
        refreshData()
      }
    }, 5 * 60 * 1000) // 5分钟
    ElMessage.success('已启用自动刷新 (5分钟间隔)')
  } else {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
    ElMessage.info('已禁用自动刷新')
  }
}

// 时间范围变化处理
const onTimeRangeChange = (value: string) => {
  if (value !== 'custom') {
    updateTimeFromRange(value)
    refreshChartsData()
  }
}

// 自定义时间变化处理
const onCustomTimeChange = (value: any) => {
  if (value && value.length === 2) {
    timeFrom.value = value[0]
    timeTo.value = value[1]
    refreshChartsData()
  }
}

// 根据时间范围更新时间参数
const updateTimeFromRange = (range: string) => {
  const now = new Date()
  timeTo.value = now.toISOString()

  switch (range) {
    case '1h':
      timeFrom.value = new Date(now.getTime() - 1 * 60 * 60 * 1000).toISOString()
      break
    case '6h':
      timeFrom.value = new Date(now.getTime() - 6 * 60 * 60 * 1000).toISOString()
      break
    case '12h':
      timeFrom.value = new Date(now.getTime() - 12 * 60 * 60 * 1000).toISOString()
      break
    case '24h':
      timeFrom.value = new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString()
      break
    case '3d':
      timeFrom.value = new Date(now.getTime() - 3 * 24 * 60 * 60 * 1000).toISOString()
      break
    case '7d':
      timeFrom.value = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString()
      break
    default:
      timeFrom.value = new Date(now.getTime() - 6 * 60 * 60 * 1000).toISOString()
  }
}



// 渲染图表
const renderChart = async (chart: any) => {
  if (chart.loading || loadingCharts.has(chart.id)) return

  chart.loading = true
  loadingCharts.add(chart.id)

  try {
    await nextTick()
    const chartDom = document.getElementById(`chart-${chart.id}`)
    if (!chartDom) {
      console.warn(`图表容器未找到: chart-${chart.id}`)
      return
    }

    let chartInstance = chartInstances.get(chart.id)
    if (!chartInstance) {
      chartInstance = echarts.init(chartDom, 'dark')
      chartInstances.set(chart.id, chartInstance)
    }

    // 获取真实的图表数据
    let realData = null
    const timeParams = getTimeParams()
    const cacheKey = `${chart.id}_${JSON.stringify(timeParams)}`

    // 检查缓存
    if (chartDataCache.has(cacheKey)) {
      realData = chartDataCache.get(cacheKey)
      console.log(`图表 ${chart.name} 使用缓存数据`)
    } else {
      try {
        const response = await monitoringApi.getDashboardGraphData({
          graph_id: chart.id,
          ...timeParams
        })

        if (response.data && response.data.success) {
          realData = response.data.data
          // 缓存数据，5分钟过期
          chartDataCache.set(cacheKey, realData)
          setTimeout(() => chartDataCache.delete(cacheKey), 5 * 60 * 1000)
          console.log(`图表 ${chart.name} 获取到真实数据:`, realData)
        }
      } catch (error) {
        console.warn(`图表 ${chart.name} 获取数据失败，使用模拟数据:`, error)
      }
    }

    // 根据图表名称智能选择图表类型和配置
    const chartType = getChartType(chart.name)
    const option = generateChartOption(chart, chartType, realData)

    if (chartInstance && option) {
      chartInstance.setOption(option, true)
    }

  } catch (error) {
    console.error('渲染图表失败:', error, chart)
  } finally {
    chart.loading = false
    loadingCharts.delete(chart.id)
  }
}

// 获取时间参数
const getTimeParams = () => {
  if (timeRange.value === 'custom' && customTimeRange.value.length === 2) {
    return {
      time_from: new Date(customTimeRange.value[0]).getTime() / 1000,
      time_to: new Date(customTimeRange.value[1]).getTime() / 1000
    }
  } else {
    return {
      time_from: `now-${timeRange.value}`,
      time_to: 'now'
    }
  }
}

// 批量渲染图表，避免同时发起太多请求
const renderChartsInBatches = async (chartList: any[]) => {
  const batchSize = 3 // 每批处理3个图表
  const batches = []

  for (let i = 0; i < chartList.length; i += batchSize) {
    batches.push(chartList.slice(i, i + batchSize))
  }

  for (const batch of batches) {
    // 并行处理当前批次的图表
    await Promise.all(batch.map(chart => renderChart(chart)))
    // 批次间稍微延迟，避免服务器压力过大
    if (batches.indexOf(batch) < batches.length - 1) {
      await new Promise(resolve => setTimeout(resolve, 200))
    }
  }
}

// 智能选择图表类型 - 更多样化
const getChartType = (chartName: string) => {
  const name = chartName.toLowerCase()

  if (name.includes('cpu') || name.includes('processor')) {
    return 'gauge' // 仪表盘
  } else if (name.includes('memory') || name.includes('内存')) {
    return 'liquidFill' // 水球图
  } else if (name.includes('disk') || name.includes('磁盘')) {
    return 'pie' // 饼图
  } else if (name.includes('network') || name.includes('网络')) {
    return 'area' // 面积图
  } else if (name.includes('load') || name.includes('负载')) {
    return 'radar' // 雷达图
  } else if (name.includes('temperature') || name.includes('温度')) {
    return 'thermometer' // 温度计
  } else if (name.includes('process') || name.includes('进程')) {
    return 'funnel' // 漏斗图
  } else if (name.includes('swap') || name.includes('交换')) {
    return 'polar' // 极坐标图
  } else if (name.includes('interface') || name.includes('接口')) {
    return 'scatter' // 散点图
  } else if (name.includes('login') || name.includes('登录') || name.includes('user')) {
    return 'simple-line' // 简洁折线图
  } else {
    return 'line' // 默认折线图
  }
}

// 生成高端图表配置
const generateChartOption = (chart: any, type: string, realData: any = null) => {
  const baseOption = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#4facfe',
      borderWidth: 1,
      textStyle: { color: '#fff' }
    },
    grid: {
      left: '10%',
      right: '10%',
      top: '5%',
      bottom: '5%',
      containLabel: true
    }
  }

  // 处理真实数据或生成模拟数据
  let times = []
  let seriesData = []
  let hasRealData = false

  if (realData && realData.series && realData.series.length > 0) {
    // 使用真实数据
    hasRealData = true

    // 收集所有时间点并去重排序
    const allTimestamps = new Set()
    realData.series.forEach(series => {
      if (series.data && series.data.length > 0) {
        series.data.forEach(point => allTimestamps.add(point[0]))
      }
    })

    const sortedTimestamps = Array.from(allTimestamps).sort((a, b) => a - b)
    times = sortedTimestamps.map(timestamp => {
      const date = new Date(timestamp)
      return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    })

    // 处理每个系列的数据
    seriesData = realData.series.map(series => {
      // 创建时间戳到值的映射
      const dataMap = new Map()
      if (series.data && series.data.length > 0) {
        series.data.forEach(point => {
          dataMap.set(point[0], point[1])
        })
      }

      // 为每个时间点填充数据，没有数据的点用null
      const alignedData = sortedTimestamps.map(timestamp =>
        dataMap.has(timestamp) ? dataMap.get(timestamp) : null
      )

      return {
        name: series.name,
        data: alignedData,
        color: series.color || '#4facfe',
        units: series.units || ''
      }
    })

    console.log(`图表 ${chart.name} 处理后的真实数据:`, { times: times.length, series: seriesData.length })
  }

  // 如果没有真实数据，生成模拟数据
  if (!hasRealData) {
    const now = new Date()
    times = Array.from({ length: 24 }, (_, i) => {
      const time = new Date(now.getTime() - (23 - i) * 60 * 60 * 1000)
      return time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    })
    console.log(`图表 ${chart.name} 使用模拟数据`)
  }

  // 生成真实的数据值
  const generateRealisticData = (type: string) => {
    switch (type) {
      case 'cpu':
        return Array.from({ length: 24 }, () => Math.random() * 80 + 10) // 10-90%
      case 'memory':
        return Array.from({ length: 24 }, () => Math.random() * 60 + 20) // 20-80%
      case 'disk':
        return Array.from({ length: 24 }, () => Math.random() * 40 + 30) // 30-70%
      case 'network':
        return Array.from({ length: 24 }, () => Math.random() * 1000) // 0-1000 MB/s
      default:
        return Array.from({ length: 24 }, () => Math.random() * 100)
    }
  }

  switch (type) {
    case 'gauge':
      const cpuValue = Math.random() * 80 + 10
      return {
        ...baseOption,
        series: [{
          type: 'gauge',
          radius: '75%',
          axisLine: {
            lineStyle: {
              width: 15,
              color: [
                [0.3, '#67e0e3'],
                [0.7, '#37a2da'],
                [1, '#fd666d']
              ]
            }
          },
          pointer: {
            itemStyle: { color: 'auto' }
          },
          axisTick: { distance: -15, length: 6 },
          splitLine: { distance: -15, length: 15 },
          axisLabel: { distance: -35, color: '#fff', fontSize: 12 },
          detail: {
            valueAnimation: true,
            formatter: '{value}%',
            color: '#fff',
            fontSize: 18
          },
          data: [{ value: cpuValue.toFixed(1), name: 'CPU使用率' }]
        }]
      }

    case 'liquidFill':
      const memoryUsed = Math.random() * 60 + 20
      const memoryFree = 100 - memoryUsed
      return {
        ...baseOption,
        series: [{
          type: 'pie',
          radius: ['30%', '70%'],
          center: ['50%', '50%'],
          data: [
            {
              value: memoryUsed.toFixed(1),
              name: '已使用',
              itemStyle: {
                color: {
                  type: 'linear',
                  x: 0, y: 0, x2: 0, y2: 1,
                  colorStops: [
                    { offset: 0, color: '#4facfe' },
                    { offset: 1, color: '#00f2fe' }
                  ]
                }
              }
            },
            {
              value: memoryFree.toFixed(1),
              name: '可用',
              itemStyle: {
                color: {
                  type: 'linear',
                  x: 0, y: 0, x2: 0, y2: 1,
                  colorStops: [
                    { offset: 0, color: 'rgba(255,255,255,0.3)' },
                    { offset: 1, color: 'rgba(255,255,255,0.1)' }
                  ]
                }
              }
            }
          ],
          label: {
            show: true,
            color: '#fff',
            formatter: '{b}: {c}%'
          },
          labelLine: {
            show: true,
            lineStyle: { color: '#fff' }
          }
        }]
      }

    case 'pie':
      const diskUsed = Math.random() * 60 + 20
      const diskFree = 100 - diskUsed
      return {
        ...baseOption,
        title: {
          ...baseOption.title,
          subtext: `磁盘使用: ${diskUsed.toFixed(1)}% | 可用: ${diskFree.toFixed(1)}%`,
          subtextStyle: { color: 'rgba(255,255,255,0.7)', fontSize: 12 }
        },
        series: [{
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            color: '#fff',
            formatter: '{b}: {c}%'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          data: [
            { value: diskUsed.toFixed(1), name: '已使用', itemStyle: { color: '#fd666d' } },
            { value: diskFree.toFixed(1), name: '可用', itemStyle: { color: '#37a2da' } }
          ]
        }]
      }

    case 'area':
      const networkData = generateRealisticData('network')
      const avgSpeed = (networkData.reduce((a, b) => a + b, 0) / networkData.length).toFixed(1)
      return {
        ...baseOption,
        title: {
          ...baseOption.title,
          subtext: `平均速度: ${avgSpeed} MB/s | 峰值: ${Math.max(...networkData).toFixed(1)} MB/s`,
          subtextStyle: { color: 'rgba(255,255,255,0.7)', fontSize: 12 }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: times,
          axisLabel: { color: '#fff' }
        },
        yAxis: {
          type: 'value',
          axisLabel: { color: '#fff', formatter: '{value} MB/s' }
        },
        series: [{
          type: 'line',
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(79, 172, 254, 0.8)' },
                { offset: 1, color: 'rgba(79, 172, 254, 0.1)' }
              ]
            }
          },
          lineStyle: { color: '#4facfe', width: 3 },
          symbol: 'circle',
          symbolSize: 6,
          data: networkData
        }]
      }

    case 'radar':
      const loadData = [
        Math.random() * 5,
        Math.random() * 5,
        Math.random() * 5,
        Math.random() * 5,
        Math.random() * 5
      ]
      return {
        ...baseOption,
        radar: {
          indicator: [
            { name: '1分钟', max: 5 },
            { name: '5分钟', max: 5 },
            { name: '15分钟', max: 5 },
            { name: 'CPU', max: 5 },
            { name: '内存', max: 5 }
          ],
          axisName: { color: '#fff', fontSize: 12 },
          splitLine: { lineStyle: { color: 'rgba(255,255,255,0.3)' } },
          splitArea: { show: false },
          radius: '70%'
        },
        series: [{
          type: 'radar',
          data: [{
            value: loadData,
            name: '系统负载',
            areaStyle: {
              color: 'rgba(67, 233, 123, 0.3)'
            },
            lineStyle: { color: '#43e97b', width: 2 }
          }]
        }]
      }

    case 'thermometer':
      const tempValue = Math.random() * 40 + 30 // 30-70度
      return {
        ...baseOption,
        title: {
          ...baseOption.title,
          subtext: `当前温度: ${tempValue.toFixed(1)}°C | 正常范围: 30-60°C`,
          subtextStyle: { color: 'rgba(255,255,255,0.7)', fontSize: 12 }
        },
        series: [{
          type: 'gauge',
          radius: '80%',
          min: 0,
          max: 100,
          axisLine: {
            lineStyle: {
              width: 20,
              color: [
                [0.6, '#67e0e3'],
                [0.8, '#f59e0b'],
                [1, '#fd666d']
              ]
            }
          },
          pointer: {
            itemStyle: { color: 'auto' }
          },
          axisTick: { distance: -20, length: 8 },
          splitLine: { distance: -20, length: 20 },
          axisLabel: { distance: -40, color: '#fff', formatter: '{value}°C' },
          detail: {
            valueAnimation: true,
            formatter: '{value}°C',
            color: '#fff',
            fontSize: 20
          },
          data: [{ value: tempValue.toFixed(1), name: '温度' }]
        }]
      }

    case 'funnel':
      // 改为堆叠柱状图，更美观
      const processData = [100, 80, 60, 40, 20]
      const processNames = ['总进程', '运行中', '活跃', '高优先级', '系统进程']
      return {
        ...baseOption,
        xAxis: {
          type: 'category',
          data: processNames,
          axisLabel: { color: '#fff', fontSize: 10, rotate: 45 }
        },
        yAxis: {
          type: 'value',
          axisLabel: { color: '#fff', fontSize: 10 }
        },
        series: [{
          type: 'bar',
          data: processData.map((value, index) => ({
            value,
            itemStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57'][index] },
                  { offset: 1, color: ['#ee5a52', '#26d0ce', '#3742fa', '#2ed573', '#ff9ff3'][index] }
                ]
              },
              borderRadius: [4, 4, 0, 0]
            }
          })),
          barWidth: '60%'
        }]
      }

    case 'polar':
      const swapData = Array.from({ length: 12 }, (_, i) => [i, Math.random() * 100])
      return {
        ...baseOption,
        title: {
          ...baseOption.title,
          subtext: `交换分区使用情况 | 平均: ${(swapData.reduce((a, b) => a + b[1], 0) / swapData.length).toFixed(1)}%`,
          subtextStyle: { color: 'rgba(255,255,255,0.7)', fontSize: 12 }
        },
        polar: {
          radius: [20, '80%']
        },
        radiusAxis: {
          max: 100,
          axisLabel: { color: '#fff' }
        },
        angleAxis: {
          type: 'category',
          data: ['0', '2', '4', '6', '8', '10', '12', '14', '16', '18', '20', '22'],
          axisLabel: { color: '#fff' }
        },
        series: [{
          type: 'bar',
          data: swapData,
          coordinateSystem: 'polar',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: '#f093fb' },
                { offset: 1, color: '#f5576c' }
              ]
            }
          }
        }]
      }

    case 'scatter':
      const scatterData = Array.from({ length: 50 }, () => [
        Math.random() * 100,
        Math.random() * 100,
        Math.random() * 50 + 10
      ])
      return {
        ...baseOption,
        title: {
          ...baseOption.title,
          subtext: `接口响应时间分布 | 数据点: ${scatterData.length}个`,
          subtextStyle: { color: 'rgba(255,255,255,0.7)', fontSize: 12 }
        },
        xAxis: {
          type: 'value',
          axisLabel: { color: '#fff', formatter: '{value}ms' }
        },
        yAxis: {
          type: 'value',
          axisLabel: { color: '#fff', formatter: '{value}%' }
        },
        series: [{
          type: 'scatter',
          symbolSize: function (data) {
            return data[2] / 2
          },
          data: scatterData,
          itemStyle: {
            color: {
              type: 'radial',
              x: 0.5, y: 0.5, r: 0.5,
              colorStops: [
                { offset: 0, color: '#43e97b' },
                { offset: 1, color: '#38f9d7' }
              ]
            }
          }
        }]
      }

    case 'bar':
      return {
        ...baseOption,
        xAxis: {
          type: 'category',
          data: times.filter((_, i) => i % 4 === 0), // 每4小时一个点
          axisLabel: { color: '#fff' }
        },
        yAxis: {
          type: 'value',
          axisLabel: { color: '#fff', formatter: '{value}%' }
        },
        series: [{
          type: 'bar',
          data: generateRealisticData('disk').filter((_, i) => i % 4 === 0),
          itemStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: '#43e97b' },
                { offset: 1, color: '#38f9d7' }
              ]
            },
            borderRadius: [4, 4, 0, 0]
          }
        }]
      }

    case 'simple-line': // 简洁折线图 - 用于登录数量等单一指标
      return {
        ...baseOption,
        grid: {
          left: '10%',
          right: '10%',
          top: '15%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: times,
          axisLabel: { color: '#fff', fontSize: 10 },
          axisLine: { lineStyle: { color: '#4facfe' } }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#fff',
            fontSize: 10,
            formatter: (value) => {
              if (hasRealData && seriesData.length > 0) {
                const firstSeries = seriesData[0]
                const unit = firstSeries.units || ''
                return unit ? `${value}${unit}` : value
              }
              return value
            }
          },
          axisLine: { lineStyle: { color: '#4facfe' } },
          splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
        },
        series: hasRealData && seriesData.length > 0 ?
          seriesData.map(item => ({
            name: item.name,
            type: 'line',
            smooth: true,
            lineStyle: { color: item.color || '#4facfe', width: 3 },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: item.color || '#4facfe' },
                  { offset: 1, color: 'transparent' }
                ]
              }
            },
            symbol: 'circle',
            symbolSize: 6,
            data: item.data
          })) :
          [{
            name: '数据',
            type: 'line',
            smooth: true,
            lineStyle: { color: '#4facfe', width: 3 },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: '#4facfe' },
                  { offset: 1, color: 'transparent' }
                ]
              }
            },
            symbol: 'circle',
            symbolSize: 6,
            data: generateRealisticData('default')
          }]
      }

    default: // line - 多条数据线，像Zabbix一样
      let finalSeriesData = []

      if (hasRealData && seriesData.length > 0) {
        // 使用真实数据
        finalSeriesData = seriesData
        console.log(`图表 ${chart.name} 使用真实数据，共 ${seriesData.length} 个系列`)
      } else {
        // 使用模拟数据
        finalSeriesData = [
          {
            name: 'guest nice time',
            data: generateRealisticData('cpu'),
            color: '#ff6b6b',
            units: '%'
          },
          {
            name: 'guest time',
            data: generateRealisticData('cpu'),
            color: '#4ecdc4',
            units: '%'
          },
          {
            name: 'interrupt time',
            data: generateRealisticData('cpu'),
            color: '#45b7d1',
            units: '%'
          },
          {
            name: 'nice time',
            data: generateRealisticData('cpu'),
            color: '#96ceb4',
            units: '%'
          },
          {
            name: 'softirq time',
            data: generateRealisticData('cpu'),
            color: '#feca57',
            units: '%'
          },
          {
            name: 'steal time',
            data: generateRealisticData('cpu'),
            color: '#ff9ff3',
            units: '%'
          },
          {
            name: 'system time',
            data: generateRealisticData('cpu'),
            color: '#54a0ff',
            units: '%'
          },
          {
            name: 'user time',
            data: generateRealisticData('cpu'),
            color: '#5f27cd',
            units: '%'
          }
        ]
        console.log(`图表 ${chart.name} 使用模拟数据`)
      }

      return {
        ...baseOption,
        grid: {
          left: '10%',
          right: '10%',
          top: '5%',
          bottom: '5%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: times,
          axisLabel: { color: '#fff', fontSize: 10 }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#fff',
            fontSize: 10,
            formatter: (value) => {
              // 根据真实数据的单位进行格式化
              if (hasRealData && finalSeriesData.length > 0) {
                const firstSeries = finalSeriesData[0]
                const unit = firstSeries.units || ''
                return unit ? `${value}${unit}` : value
              }
              return `${value}%` // 默认百分比
            }
          }
        },
        series: finalSeriesData.map(item => ({
          name: item.name,
          type: 'line',
          smooth: true,
          lineStyle: { color: item.color, width: 2 },
          symbol: 'none',
          data: item.data
        }))
      }
  }
}

// 刷新单个图表
const refreshChart = async (chartId: string) => {
  const chart = charts.value.find(c => c.id === chartId)
  if (chart) {
    await renderChart(chart)
  }
}

// 刷新数据
const refreshData = async () => {
  if (!selectedHostId.value) {
    ElMessage.warning('请先选择主机')
    return
  }

  loading.value = true
  try {
    // 刷新当前选择的主机数据，而不是重新初始化
    await Promise.all([
      fetchHostMetrics(selectedHostId.value),
      loadHostCharts(selectedHostId.value)
    ])
    ElMessage.success(`主机 ${selectedHostName.value} 数据刷新成功`)
  } catch (error) {
    console.error('数据刷新失败:', error)
    ElMessage.error('数据刷新失败')
  } finally {
    loading.value = false
  }
}

// 刷新所有图表
const refreshAllCharts = async () => {
  const promises = charts.value.map(chart => renderChart(chart))
  await Promise.all(promises)
}

// 初始化数据 - 加载主机组并默认显示Zabbix server数据
const initData = async () => {
  loading.value = true
  try {
    // 1. 加载主机组列表
    await loadHostGroups()

    // 2. 默认加载Zabbix Server数据
    selectedHostId.value = '10084'
    selectedHostName.value = 'Zabbix server'
    hostStatus.value = '在线'

    await Promise.all([
      fetchHostMetrics('10084'),
      loadHostCharts('10084')
    ])

    ElMessage.success('监控仪表盘加载完成')
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('加载监控数据失败')
  } finally {
    loading.value = false
  }
}

// 加载主机组列表
const loadHostGroups = async () => {
  groupLoading.value = true
  try {
    // 使用正确的仪表盘API
    const response = await monitoringApi.getDashboardHostGroups()
    if (response.data && response.data.success && response.data.data.length > 0) {
      hostGroups.value = response.data.data.map(group => ({
        groupid: group.id,
        name: group.name
      }))

      // 查找并默认选择Zabbix servers主机组
      const zabbixGroup = hostGroups.value.find(group =>
        group.name.toLowerCase().includes('zabbix')
      )

      if (zabbixGroup) {
        selectedGroupId.value = zabbixGroup.groupid
        await loadGroupHosts(zabbixGroup.groupid)

        // 自动选择Zabbix server主机
        setTimeout(() => {
          const zabbixHost = hosts.value.find(host =>
            host.hostid === '10084' ||
            host.name.toLowerCase().includes('zabbix server')
          )
          if (zabbixHost) {
            selectedHostId.value = zabbixHost.hostid
          }
        }, 100)
      }

      console.log('主机组加载完成:', hostGroups.value)
    }
  } catch (error) {
    console.error('获取主机组失败:', error)
    ElMessage.error('获取主机组失败，请检查网络连接')
  } finally {
    groupLoading.value = false
  }
}

// 加载主机组下的主机
const loadGroupHosts = async (groupId: string) => {
  try {
    const response = await monitoringApi.getDashboardHosts({ group_id: groupId })
    if (response.data && response.data.success && response.data.data.length > 0) {
      hosts.value = response.data.data.map(host => ({
        hostid: host.id,
        name: host.name,
        host: host.host,
        status: host.status
      }))
    }
  } catch (error) {
    console.error('获取主机列表失败:', error)
  }
}

// 获取主机监控项
const fetchHostItems = async (hostId: string) => {
  if (!hostId) return

  try {
    console.log('获取主机监控项:', hostId)
    const response = await monitoringApi.getHostItems(hostId)
    if (response.data && response.data.success) {
      console.log('获取到监控项:', response.data.data?.length || 0, '个')
      // 这里可以根据需要处理监控项数据
      // 目前仪表盘主要显示图表，监控项数据可以用于其他用途
    } else {
      console.warn('获取监控项失败:', response.data?.message)
    }
  } catch (error) {
    console.error('获取主机监控项失败:', error)
    // 不显示错误消息，避免影响用户体验
  }
}

// 移除死循环的监听器 - 不需要自动重新渲染

// 生命周期钩子
onMounted(() => {
  updateTime()
  timeTimer = setInterval(updateTime, 1000)

  // 初始化时间范围
  updateTimeFromRange(timeRange.value)

  initData()
})

onUnmounted(() => {
  if (refreshTimer) clearInterval(refreshTimer)
  if (timeTimer) clearInterval(timeTimer)

  chartInstances.forEach(chart => {
    chart.dispose()
  })
  chartInstances.clear()
})
</script>

<style lang="scss" scoped>
.zabbix-dashboard {
  min-height: 100vh;
  background: linear-gradient(135deg, #0c0c0c 0%, #1a1a2e 50%, #16213e 100%);
  position: relative;
  overflow: hidden;
}

// 星空背景动画
.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent),
    radial-gradient(1px 1px at 130px 80px, rgba(255,255,255,0.6), transparent),
    radial-gradient(2px 2px at 160px 30px, #ddd, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite linear;
}

.stars2 {
  background-image:
    radial-gradient(1px 1px at 40px 60px, #fff, transparent),
    radial-gradient(1px 1px at 120px 10px, rgba(255,255,255,0.9), transparent),
    radial-gradient(1px 1px at 170px 50px, rgba(255,255,255,0.7), transparent);
  background-repeat: repeat;
  background-size: 250px 120px;
  animation: zoom 40s infinite linear;
}

.stars3 {
  background-image:
    radial-gradient(1px 1px at 10px 10px, #fff, transparent),
    radial-gradient(2px 2px at 150px 90px, rgba(255,255,255,0.5), transparent),
    radial-gradient(1px 1px at 60px 70px, rgba(255,255,255,0.8), transparent);
  background-repeat: repeat;
  background-size: 300px 150px;
  animation: zoom 60s infinite linear;
}

@keyframes zoom {
  from {
    transform: scale(0);
  }
  to {
    transform: scale(1);
  }
}

// 玻璃效果
.glass-effect {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="20" cy="20" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="80" cy="40" r="0.5" fill="rgba(255,255,255,0.1)"/><circle cx="40" cy="60" r="1" fill="rgba(255,255,255,0.1)"/></svg>') repeat;
    animation: twinkle 20s linear infinite;
    pointer-events: none;
  }

  @keyframes twinkle {
    0%, 100% { opacity: 0.3; }
    50% { opacity: 0.8; }
  }
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  z-index: 10;

  .header-left {
    display: flex;
    align-items: center;
    gap: 20px;

    .dashboard-title {
      color: #fff;
      font-size: 24px;
      font-weight: 600;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 10px;

      i {
        color: #4facfe;
        font-size: 28px;
      }
    }

    .time-display {
      color: rgba(255, 255, 255, 0.8);
      font-size: 14px;
      font-family: 'Courier New', monospace;
      background: rgba(255, 255, 255, 0.1);
      padding: 8px 12px;
      border-radius: 20px;
      border: 1px solid rgba(255, 255, 255, 0.2);
    }
  }

  .header-controls {
    display: flex;
    align-items: center;
    gap: 20px;

    .selector-group {
      display: flex;
      flex-direction: column;
      gap: 5px;

      label {
        color: rgba(255, 255, 255, 0.8);
        font-size: 12px;
        font-weight: 500;
      }

      .dashboard-select {
        min-width: 150px;

        :deep(.el-input__inner) {
          background: rgba(255, 255, 255, 0.1);
          border: 1px solid rgba(255, 255, 255, 0.3);
          color: #fff;

          &::placeholder {
            color: rgba(255, 255, 255, 0.6);
          }
        }


      }

      &.time-selector {
        min-width: 150px;
      }

      &.custom-time {
        min-width: 350px;

        :deep(.el-date-editor) {
          background: rgba(255, 255, 255, 0.1);
          border: 1px solid rgba(255, 255, 255, 0.3);

          .el-input__inner {
            background: transparent;
            border: none;
            color: #fff;

            &::placeholder {
              color: rgba(255, 255, 255, 0.6);
            }
          }
        }
      }
    }

    .control-buttons {
      display: flex;
      align-items: center;
      gap: 15px;

      .refresh-btn {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        border: none;
        color: #fff;
        font-weight: 500;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(79, 172, 254, 0.3);
        }
      }

      .auto-refresh-switch {
        :deep(.el-switch__label) {
          color: #fff;
          font-size: 12px;
        }
      }
    }
  }
}

.dashboard-main {
  padding: 30px;
  position: relative;
  z-index: 5;
}

.host-overview {
  margin-bottom: 30px;

  .overview-card {
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(20px);
    border-radius: 20px;
    border: 1px solid rgba(255, 255, 255, 0.2);
    padding: 25px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h3 {
        color: #fff;
        font-size: 20px;
        font-weight: 600;
        margin: 0;
      }

      .host-status {
        padding: 8px 16px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
        text-transform: uppercase;
        display: flex;
        align-items: center;
        gap: 8px;

        &.online {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          color: #fff;
        }

        &.offline {
          background: linear-gradient(135deg, #fd666d 0%, #f093fb 100%);
          color: #fff;
        }

        &.unknown {
          background: linear-gradient(135deg, #909399 0%, #b3b3b3 100%);
          color: #fff;
        }

        i {
          font-size: 8px;
        }
      }
    }

    .card-content {
      .metric-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;

        .metric-item {
          display: flex;
          align-items: center;
          gap: 15px;
          padding: 15px;
          background: rgba(255, 255, 255, 0.05);
          border-radius: 15px;
          border: 1px solid rgba(255, 255, 255, 0.1);
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
          }

          .metric-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 20px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
          }

          .metric-info {
            flex: 1;

            .metric-value {
              color: #fff;
              font-size: 18px;
              font-weight: 700;
              margin-bottom: 4px;
            }

            .metric-label {
              color: rgba(255, 255, 255, 0.7);
              font-size: 12px;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
}

// 图表容器
.charts-container {
  margin-top: 30px;

  .chart-group {
    margin-bottom: 40px;
    padding: 25px;
    border-radius: 20px;

    .group-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;
      padding-bottom: 15px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.2);

      .group-title {
        color: #fff;
        font-size: 20px;
        font-weight: 600;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 10px;

        i {
          color: #4facfe;
          font-size: 22px;
        }
      }

      .group-count {
        color: rgba(255, 255, 255, 0.7);
        font-size: 14px;
        background: rgba(255, 255, 255, 0.1);
        padding: 6px 12px;
        border-radius: 15px;
        border: 1px solid rgba(255, 255, 255, 0.2);

        .filter-info {
          color: #4facfe;
          font-weight: 600;
          margin-left: 5px;
        }
      }
    }
  }
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 25px;

  .chart-card {
    background: rgba(255, 255, 255, 0.08);
    backdrop-filter: blur(20px);
    border-radius: 20px;
    border: 1px solid rgba(255, 255, 255, 0.15);
    overflow: hidden;
    transition: all 0.3s ease;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 15px 40px rgba(0, 0, 0, 0.2);
      border-color: rgba(255, 255, 255, 0.3);
    }

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding: 20px 25px 15px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      .chart-title-group {
        flex: 1;

        .chart-title {
          color: #fff;
          font-size: 16px;
          font-weight: 600;
          margin: 0 0 8px 0;
          line-height: 1.3;
        }

        .chart-meta {
          display: flex;
          gap: 10px;
          align-items: center;

          .chart-type {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: #fff;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 10px;
            font-weight: 600;
            text-transform: uppercase;
          }

          .chart-unit {
            color: rgba(255, 255, 255, 0.6);
            font-size: 12px;
            font-weight: 500;
          }
        }
      }

      .chart-actions {
        display: flex;
        gap: 8px;

        .el-button {
          background: rgba(255, 255, 255, 0.1);
          border: 1px solid rgba(255, 255, 255, 0.2);
          color: rgba(255, 255, 255, 0.8);
          width: 32px;
          height: 32px;

          &:hover {
            background: rgba(255, 255, 255, 0.2);
            color: #fff;
            transform: scale(1.1);
          }
        }
      }
    }

    .chart-content {
      height: 300px;
      padding: 15px;
      position: relative;
    }

    .chart-description {
      padding: 15px 20px;
      border-top: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(255, 255, 255, 0.05);

      .data-metrics {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;

        .metric-item {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 12px;
          color: #fff;

          .metric-color {
            width: 12px;
            height: 12px;
            border-radius: 2px;
            flex-shrink: 0;
          }

          .metric-name {
            color: rgba(255, 255, 255, 0.8);
            min-width: 80px;
          }

          .metric-value {
            color: #fff;
            font-weight: 600;
            font-family: 'Courier New', monospace;
          }
        }
      }
    }
  }
}

.empty-state,
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  text-align: center;
  padding: 60px 20px;

  .empty-icon,
  .loading-icon {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 30px;
    box-shadow: 0 15px 35px rgba(79, 172, 254, 0.3);

    i {
      font-size: 48px;
      color: #fff;
    }
  }

  .loading-icon {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    box-shadow: 0 15px 35px rgba(67, 233, 123, 0.3);
  }

  h2, h3 {
    color: #fff;
    font-size: 28px;
    font-weight: 600;
    margin: 0 0 15px 0;
  }

  h3 {
    font-size: 24px;
  }

  p {
    color: rgba(255, 255, 255, 0.7);
    font-size: 16px;
    line-height: 1.6;
    max-width: 500px;
    margin: 0;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .charts-grid {
    grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
    gap: 20px;
  }

  .host-overview .overview-card .card-content .metric-grid {
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 15px;
  }
}

@media (max-width: 768px) {
  .dashboard-header {
    flex-direction: column;
    gap: 20px;
    padding: 20px;

    .header-controls {
      flex-wrap: wrap;
      justify-content: center;
    }
  }

  .charts-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }

  .host-overview .overview-card .card-content .metric-grid {
    grid-template-columns: 1fr;
  }

  .dashboard-main {
    padding: 20px 15px;
  }
}
</style>
